package atm;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

/**
 * 转账界面
 */
public class TransferPanel extends JPanel implements ActionListener {
    private ATMFrame atmFrame;
    private JLabel otherAccountLabel = new JLabel();
    private JTextField otherAccountField = new JTextField();
    private JLabel blanceLabel = new JLabel();
    private JTextField blanceField = new JTextField();
    private JButton sureBtn = new JButton(new ImageIcon("images/buttonSure.jpg"));
    private Font font = new Font("黑体",Font.BOLD,30);
    public TransferPanel(ATMFrame atmFrame){
        this.atmFrame = atmFrame;
        this.setLayout(null);
        otherAccountLabel.setBounds(300,200,300,50);
        otherAccountLabel.setFont(font);
        otherAccountLabel.setText("请输入对方账号：");

        otherAccountField.setBounds(600,200,200,50);
        otherAccountField.setFont(font);

        blanceLabel.setBounds(300,270,300,50);
        blanceLabel.setFont(font);
        blanceLabel.setText("请输入转账金额：");

        blanceField.setBounds(600,270,200,50);
        blanceField.setFont(font);

        sureBtn.setBounds(350,400,140,50);
        sureBtn.addActionListener(this);

        this.add(otherAccountLabel);
        this.add(otherAccountField);
        this.add(blanceLabel);
        this.add(blanceField);
        this.add(sureBtn);
        this.setOpaque(false);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        User loginUser = atmFrame.getLoginUser();
        if (e.getSource() == sureBtn) {
            if(Double.parseDouble(blanceField.getText()) > loginUser.getBlance()){
                JOptionPane.showMessageDialog(this,"余额不足");
                return;
            }
            if(otherAccountField.getText().equals(loginUser.getAccount())){
                JOptionPane.showMessageDialog(this,"不能转给自己");
                return;
            }
            // 查询对方账户是否存在
            UserDao userDao = new UserDao();
            User otherUser = userDao.findByAccount(otherAccountField.getText());
            if(otherUser == null){
                JOptionPane.showMessageDialog(this,"输入的账号不正确");
                return;
            }
            loginUser.setBlance(loginUser.getBlance() - Double.parseDouble(blanceField.getText()));
            otherUser.setBlance(otherUser.getBlance() + Double.parseDouble(blanceField.getText()));
            // 修改数据库的数据
            userDao.update(loginUser);
            userDao.update(otherUser);
            JOptionPane.showMessageDialog(this,"转账成功");
            atmFrame.switchPanel("menu");



        }
    }
}
